#!/usr/bin/env python3
"""
Click Assistant PyInstaller 构建脚本 - 修复版本
解决了Windows上的strip警告和zipfile缺失问题
"""

import sys
import subprocess
import shutil
import platform
from pathlib import Path


def clean_old_builds():
    """清理旧的构建文件"""
    print("[构建] 清理构建缓存...")

    items_to_clean = [
        "build", "dist", "__pycache__", "*.spec", 
        "app/__pycache__", "*.pyc", "*.pyo"
    ]

    for item in items_to_clean:
        if item.endswith((".spec", ".pyc", ".pyo")):
            for file in Path(".").glob(item):
                file.unlink()
                print(f"[删除] 文件: {file.name}")
        else:
            dir_path = Path(item)
            if dir_path.exists():
                shutil.rmtree(dir_path)
                print(f"[删除] 目录: {item}")

    # 清理output目录中的旧文件
    output_dir = Path("output")
    if output_dir.exists():
        for file in output_dir.glob("*.exe"):
            file.unlink()
            print(f"[删除] 旧EXE: {file.name}")


def build_exe():
    """构建 Click Assistant EXE 文件"""
    print("[构建] 开始构建 Click Assistant EXE...")
    print(f"[构建] 操作系统: {platform.system()} {platform.release()}")

    output_dir = Path("output")
    output_dir.mkdir(exist_ok=True)

    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--onefile",
        "--windowed", 
        "--name=click-assistant",
        f"--distpath={output_dir}",
        "--workpath=.build",
        "--specpath=.build",
        "--clean",
        "--noconfirm",
        "--optimize=2",
        "--log-level=WARN",
        "--noupx",
        "--disable-windowed-traceback",
    ]
    
    # 智能处理strip参数 - 只在非Windows系统使用
    if platform.system() != "Windows":
        cmd.append("--strip")
        print("[构建] 启用调试符号去除")
    else:
        print("[构建] 跳过strip（Windows系统）")
    
    # 设置图标
    if Path("game.ico").exists():
        cmd.extend([f"--icon={Path('game.ico').absolute()}"])

    # 必要的隐藏导入 - 修复zipfile问题
    hidden_imports = [
        "zipfile",  # 修复运行时缺失问题
        "json",     # 常用标准库
        "subprocess",  # 可能需要的标准库
        "PIL._tkinter_finder",
        "pystray",
        "pynput",
        "pynput.keyboard", 
        "pynput.mouse",
        "pydirectinput",
        "winsound",
    ]

    for imp in hidden_imports:
        cmd.extend(["--hidden-import", imp])

    # 精简的排除模块列表 - 移除了zipfile和其他必要模块
    exclude_modules = [
        # GUI frameworks (not needed)
        "tkinter", "turtle", "idlelib",
        
        # Scientific computing (not needed)
        "matplotlib", "numpy", "pandas", "scipy",
        
        # Development tools (not needed) 
        "jupyter", "IPython", "notebook", "sphinx", "pytest",
        "docutils", "setuptools", "pip", "wheel", "distutils",
        "pdb", "profile", "pstats", "timeit", "trace", "tracemalloc",
        "unittest", "doctest", "test",
        
        # Network/web (not needed)
        "http", "urllib", "socket", "ssl", "email",
        
        # Database (not needed)
        "sqlite3", "dbm",
        
        # Compression (小心排除 - 保留zipfile)
        "gzip", "bz2", "lzma", "tarfile", 
        
        # XML/HTML processing (not needed)
        "xml", "html",
        
        # Async/multiprocessing (not needed)
        "asyncio", "multiprocessing", "concurrent",
        
        # Other unused modules (保守排除)
        "csv", "pickle", "calendar", "gettext", "locale",
        "mimetypes", "argparse", "cmd", "venv"
    ]

    for module in exclude_modules:
        cmd.extend(["--exclude-module", module])

    cmd.append("main.py")

    try:
        print("[构建] 执行PyInstaller命令...")
        subprocess.run(cmd, check=True)
        print("✅ 构建成功!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 构建失败: {e}")
        return False


def main():
    """主函数"""
    print("[构建] 开始构建 Click Assistant v2.0.1 EXE文件...")

    clean_old_builds()

    if not build_exe():
        return 1

    exe_path = Path("output/click-assistant.exe")
    if exe_path.exists():
        size_mb = exe_path.stat().st_size / (1024 * 1024)
        print(f"[构建] ✅ Click Assistant 构建完成!")
        print(f"[构建] 输出文件: {exe_path}")
        print(f"[构建] 文件大小: {size_mb:.1f} MB")
        print(f"[构建] 版本: v2.0.1")
        print(f"[构建] 系统: {platform.system()}")
    else:
        print("[构建] ❌ 输出文件不存在")
        return 1

    return 0


if __name__ == "__main__":
    sys.exit(main())